
import React, { Component } from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import Mock from 'mockjs';
import {Navigator} from 'react-native-deprecated-custom-components';
import {
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight,
  Image,
  Dimensions,
  ActivityIndicator,
  RefreshControl,
  AlertIOS,
} from 'react-native';

import request from '../common/request'
import config from '../common/config'
import Detail from './detail'

var width = Dimensions.get('window').width

var cacheResults = {
  nextPage: 1,
  items: [],
  total: 0
}

var Item = React.createClass({
  getInitialState(){
    var row  = this.props.row

    return {
      up: row.voted,
      row: row
    }
  },

  _up(){
    var that = this
    var up = !this.state.up
    var row = this.state.row
    var url = config.api.base + config.api.up

    var body = {
      id: row._id,
      up: up ? 'yes' : 'no',
      accessToken: 'abc'
    }

    request.post(url, body)
      .then(function(data) {
        if(data && data.success) {
          that.setState({
            up: up
          })       
        }else{
          AlertIOS.alert('点赞失败 请稍后重试')
        }
      })
      .catch(function(err){
        console.log(err)
        AlertIOS.alert('点赞失败 请稍后重试')
      })
  },

  render() {
    var row = this.state.row
    return (
       <TouchableHighlight onPress={this.props.onSelect}>
        <View style={styles.item}>
          <Text style={styles.title}>
            {row.title}
          </Text>
          <Image
            source={{ uri: row.thumb }}
            style={styles.thumb}
          >
            <Icon
              name='ios-play'
              size={28}
              style={styles.play}
            />
          </Image>
          <View style={styles.itemFooter}>
            <View style={styles.handleBox}>
              <Icon
                name={this.state.up ? 'ios-heart' : 'ios-heart-outline'}
                size={28}
                style={[this.state.up? styles.down : styles.up]}
                onPress={this._up}
              />
              <Text style={styles.handleText} onPress={this._up}>喜欢</Text>
            </View>
            <View style={styles.handleBox}>
              <Icon
                name='ios-chatboxes-outline'
                size={28}
                style={styles.comment}
              />
              <Text style={styles.handleText}>评论</Text>
            </View>
          </View>
        </View>
      </TouchableHighlight>
    )
  }
})

var List = React.createClass({
  getInitialState: function () {
    var ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    })

    return {
      isLoadingTail: false,
      isRefreshing: false,
      dataSource: ds.cloneWithRows([])
    }
  },

  _renderRow(row) {
    return (
      <Item 
      key={row._id} 
      onSelect={()=>this._loadPage(row)}  
      row={row} />
    )
  },

  componentDidMount: function () {
    this._fetchData(1)
  },

  _fetchData(page) {

    var that = this

    if (page !== 0) {
      this.setState({
        isLoadingTail: true
      })
    }
    else {
      this.setState({
        isRefreshing: true
      })
    }

    request.get(config.api.base + config.api.creations, {
      accessToken: 'abcdef',
      page: page
    })
      .then((data) => {
        if (data.success) {
          var items = cacheResults.items.slice()

          if (page != 0) {
            items = items.concat(data.data)
            cacheResults.nextPage += 1
          }
          else {
            items = data.data.concat(items)
          }
          items = items.concat(data.data)
          cacheResults.items = items
          cacheResults.total = data.total

          setTimeout(function () {
            if (page !== 0) {
              that.setState({
                isLoadingTail: false,
                dataSource: that.state.dataSource.cloneWithRows(cacheResults.items)
              })
            } else {
              that.setState({
                isRefreshing: false,
                dataSource: that.state.dataSource.cloneWithRows(cacheResults.items)
              })
            }
          }, 100)
        }
      })
      .catch((error) => {
        if (page !== 0) {
          this.setState({
            isLoadingTail: false,
          })
        } else {
          this.setState({
            isRefreshing: false,
          })
        }
        console.error(error);
      });
  },

  _hasMore() {
    return cacheResults.items.length !== cacheResults.total
  },

  _fetchMoreData() {
    if (!this._hasMore() || this.state.isLoadingTail) {
      return
    }

    var page = cacheResults.nextPage

    this._fetchData(page)
  },

  _onRefresh() {
    console.log(this._hasMore())
    console.log(this.state.isRefreshing)
    // if (!this._hasMore() || this.state.isRefreshing){
    if (this.state.isRefreshing) {
      return
    }

    // this.setState({
    //   isRefreshing: true
    // })

    this._fetchData(0)
  },

  _renderFooter() {
    if (!this._hasMore() && cacheResults.total !== 0) {
      return (
        <View style={styles.loadingMore}>
          <Text style={styles.loadingText}>没有更多了</Text>
        </View>
      )
    }

    // if(!this.isLoadingTail) {
    //   return <View style={styles.loadingMore} />
    // }

    return (
      <ActivityIndicator
        style={styles.loadingMore}
      />
    )
  },

  _loadPage(row){
    this.props.navigator.push({
      name: 'detail',
      component: Detail,
      params: {
        data: row
      }
    })
  },

  render: function () {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>列表页面</Text>
        </View>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          renderFooter={this._renderFooter}
          enableEmptySections={true}
          automaticallyAdjustContentInsets={false}
          onEndReached={this._fetchMoreData}
          onEndReachedThreshold={20}
          showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this._onRefresh}
              tintColor="#ff6600"
              title="拼命加载中..."
            />
          }
        />
      </View>
    )
  }
})

var styles = StyleSheet.create({
  container: {
    backgroundColor: '#F5FCFF'
  },
  header: {
    paddingTop: 25,
    paddingBottom: 12,
    backgroundColor: '#EE735C'
  },
  headerTitle: {
    color: '#FFFFFF',
    fontSize: 16,
    textAlign: 'center',
    fontWeight: '600'
  },
  item: {
    width: width,
    marginBottom: 10,
    backgroundColor: '#FFF'
  },
  title: {
    padding: 10,
    fontSize: 18,
    color: '#333'
  },
  thumb: {
    width: width,
    height: width * 0.5,
    resizeMode: 'cover'
  },
  play: {
    position: 'absolute',
    bottom: 14,
    right: 14,
    paddingTop: 9,
    paddingLeft: 18,
    borderWidth: 1,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
    width: 46,
    height: 46,
    borderRadius: 23,
    color: '#ed7b66'
  },
  itemFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    backgroundColor: '#eee'
  },
  handleBox: {
    padding: 10,
    flexDirection: 'row',
    justifyContent: 'center',
    width: width / 2 - 0.5,
    backgroundColor: '#FFF'
  },
  handleText: {
    paddingLeft: 12,
    fontSize: 18,
    color: '#333'
  },
  up: {
    fontSize: 22,
    color: '#333'
  },
  down: {
    fontSize: 22,
    color: '#EE735C'
  },
  comment: {
    fontSize: 22,
    color: '#333'
  },
  loadingMore: {
    marginVertical: 20
  },
  loadingText: {
    color: '#777',
    textAlign: 'center'
  }
});

module.exports = List